const fs = require('fs');
const path = require('path');

// 读取构建目录中的index.html文件
const buildDir = path.join(__dirname, '..', 'build');
const indexPath = path.join(buildDir, 'index.html');

// 检查文件是否存在
if (!fs.existsSync(indexPath)) {
  console.error('❌ 未找到构建后的index.html文件');
  process.exit(1);
}

// 读取文件内容
let indexContent = fs.readFileSync(indexPath, 'utf8');

// 生产环境CSP策略（更严格）
const productionCSP = [
  "default-src 'self'",
  "script-src 'self' 'wasm-unsafe-eval' https://hia.volcenginepaas.com",
  "connect-src 'self' https://hia.volcenginepaas.com https://*.volcenginepaas.com",
  "style-src 'self' 'unsafe-inline' https://hia.volcenginepaas.com",
  "img-src 'self' data: https: blob:",
  "font-src 'self' data: https://hia.volcenginepaas.com",
  "frame-src 'self' https://hia.volcenginepaas.com"
].join('; ');

// 开发环境CSP策略（更宽松）
const developmentCSP = [
  "default-src 'self'",
  "script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://hia.volcenginepaas.com chrome-extension://*",
  "connect-src 'self' http://localhost:5001 ws://localhost:* wss: https://hia.volcenginepaas.com https://*.volcenginepaas.com",
  "style-src 'self' 'unsafe-inline' https://hia.volcenginepaas.com",
  "img-src 'self' data: https: blob:",
  "font-src 'self' data: https://hia.volcenginepaas.com",
  "frame-src 'self' https://hia.volcenginepaas.com"
].join('; ');

// 替换CSP策略
indexContent = indexContent.replace(
  /<meta http-equiv="Content-Security-Policy"[^>]*>/,
  `<meta http-equiv="Content-Security-Policy" content="${productionCSP}">`
);

// 写入修改后的内容
fs.writeFileSync(indexPath, indexContent, 'utf8');

console.log('✅ CSP策略已更新为生产环境配置');